package com.neteast.androidclient.contact.widget;

import java.io.File;
import java.util.ArrayList;
import org.json.JSONObject;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.activity.ContactEditActivity;
import com.neteast.androidclient.contact.activity.MainActivity;
import com.neteast.androidclient.contact.adapter.GroupAdapter;
import com.neteast.androidclient.contact.domain.Contact;
import com.neteast.androidclient.contact.domain.ContactData;
import com.neteast.androidclient.contact.util.ImageUtil;
import com.neteast.androidclient.contact.util.JsonUtil;
import com.neteast.androidclient.contact.util.NetUtil;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 联系人信息的展示面板
 * @author tiangh
 * 2012-3-15 上午9:30:33
 */
public final class InfoDetailPanel extends LinearLayout{
	
	/**编辑联系人请求码*/
	private static final int EDIT_CONTACT = 1;
	/**设置分组成功*/
	private static final int SET_GROUP_SUCCESS=2;
	/**设置分组失败*/
	private static final int SET_GROUP_ERROR=3;
	
	private Activity context;
	/**联系人*/
	private Contact contact;
	private LayoutInflater inflater;
	private View root;
	/**是否是云好友*/
	private boolean isCloud;
	/**分组*/
	private TextView tvGroup;
	/**选择分组窗口*/
	private PopupWindow winGroup;
	/**分组的适配器*/
	private GroupAdapter groupAdapter;
	
	
	public InfoDetailPanel(Context context,Contact contact) {
		super(context);
		this.context=(Activity) context;
		this.contact=contact;
		inflater = LayoutInflater.from(context);
		root = inflater.inflate(R.layout.layout_contact_display, null);
		LinearLayout.LayoutParams params=new LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		init();
		addView(root,params);
	}

	private void init() {
		isCloud = isCloud();
		initTitle();
		initName();
		initPhoto();
		initOrg();
		initPhone();
		initEmail();
		initIM();
		initLocation();
		initGroup();
		initRemark();
		createSetGroupWindow();
	}

	/**
	 * 初始化标题栏
	 * 若是我的信息，则隐藏掉返回按钮
	 */
	private void initTitle() {
		TextView tvTitle=(TextView) root.findViewById(R.id.tv_title);
		boolean isMe=contact.ownId==contact.contactId;
		String value=isMe?"我的信息":"联系人详情";
		tvTitle.setText(value);
        View rightView = root.findViewById(R.id.rightView);
        rightView.setVisibility(View.VISIBLE);
        rightView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				 Intent intent=new Intent(context, ContactEditActivity.class);
				 intent.putExtra("isNew", false);
				 intent.putExtra("contact", contact);
				 context.startActivityForResult(intent,EDIT_CONTACT);			
			}
		});
        View btnBack = root.findViewById(R.id.btn_back);
        if (isMe) {
        	btnBack.setVisibility(View.GONE);
		}else {
			btnBack.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					context.finish();
				}
			});
		}
	}
	/**
	 * 初始化姓名
	 */
	private void initName() {
		TextView tvName=(TextView) root.findViewById(R.id.contact_name);
		tvName.setText(contact.displayName);
	}
	/**
	 * 初始化照片，若有头像，点击调用系统图库做全屏展示
	 */
	private void initPhoto() {
		ImageView ivPhoto = (ImageView) root.findViewById(R.id.contact_facepic);
		TextView tvPhoto = (TextView) root.findViewById(R.id.name_photo);
		ImageView ivFlag=(ImageView) root.findViewById(R.id.face_photo_edit);
		final String photo = ImageUtil.getPhoto(context, contact.contactId);
		if (contact.hasPhoto&&photo!=null) {
			tvPhoto.setVisibility(View.GONE);
			ivPhoto.setVisibility(View.VISIBLE);
			ivPhoto.setImageBitmap(BitmapFactory.decodeFile(photo));
		}else {
			tvPhoto.setVisibility(View.VISIBLE);
			ivPhoto.setVisibility(View.GONE);
			String name=contact.displayName;
			if (!TextUtils.isEmpty(name)) {
				tvPhoto.setText(name.substring(name.length()-1));
			}
		}
		if (contact.isReadOnly) {
			ivFlag.setVisibility(View.VISIBLE);
		}else {
			ivFlag.setVisibility(View.GONE);
		}
		root.findViewById(R.id.photo_block).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (photo!=null) {
					Intent intent = new Intent();
					intent.setAction(android.content.Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(new File(photo)), "image/*");
					context.startActivity(intent);
				}
			}
		});
	}
	/**
	 * 初始化公司信息
	 */
	private void initOrg() {
		StringBuilder sb=new StringBuilder();
		if (isNotEmpty(contact.organization)) {
			sb.append(contact.organization).append("  ");
		}
		if (isNotEmpty(contact.job)) {
			sb.append(contact.job);
		}
		String value = sb.toString();
		if (isNotEmpty(value)) {
			LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_org);
			block.setVisibility(View.VISIBLE);
			addContactDisplayItem(block,"公司",value);
		}
	}
	/**
	 * 是否不为空
	 * @param value
	 * @return
	 */
	private boolean isNotEmpty(String value) {
		return value!=null&&!"".equals(value.trim())&&!"null".equals(value.trim());
	}
	/**
	 * 初始化手机信息
	 */
	private void initPhone() {
		LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_phones);
		if (isNotEmpty(contact.fphone)) {
			addContactDisplayItem(block,"常用手机",contact.fphone);
			block.setVisibility(View.VISIBLE);
		}
		addItem(block, contact.phones);
	}
	/**
	 * 初始化邮箱信息
	 */
	private void initEmail() {
		LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_emails);
		if (isNotEmpty(contact.femail)) {
			addContactDisplayItem(block,"常用邮箱",contact.femail);
			block.setVisibility(View.VISIBLE);
		}
		addItem(block, contact.emails);
	}
	/**
	 * 初始化IM信息
	 */
	private void initIM() {
		LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_ims);
		addItem(block, contact.ims);
	}
	/**
	 * 初始化地址信息
	 */
	private void initLocation() {
		LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_locations);
		addItem(block, contact.locations);
	}
	/**
	 * 初始化分组信息
	 */
	private void initGroup() {
		tvGroup = (TextView) root.findViewById(R.id.contact_group);
		Log.i("test",contact.displayName+" contact.groups="+contact.groups);
		if (isNotEmpty(contact.groups)) {
			tvGroup.setText(contact.groups);
		}
		llGroup = root.findViewById(R.id.group_block);
		llGroup.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				showSetGroupWindow();
			}
		});
	}
	/**
	 * 初始化备注信息
	 */
	private void initRemark() {
		if (isNotEmpty(contact.remark)) {
			LinearLayout block=(LinearLayout) root.findViewById(R.id.contact_remark);
			block.setVisibility(View.VISIBLE);
			addContactDisplayItem(block, "备注", contact.remark);
		}
	}
	/**
	 * 用ArrayList<ContactData>填充容器
	 */
	public void addItem(LinearLayout showBlock,ArrayList<ContactData> datas){
		int size = datas.size();
		if (size>0) {
			showBlock.setVisibility(View.VISIBLE);
		}
		for(int i=0;i<size;i++){
			ContactData data = datas.get(i);
			if (isNotEmpty(data.content)) {
				addContactDisplayItem(showBlock, data.label, data.content);
			}
		}
	}
	/**
	 * 用ContactData填充容器
	 */
	public void addContactDisplayItem(LinearLayout showBlock,String labelValue,String contentValue) {
		LinearLayout llShowItem = (LinearLayout) inflater.inflate(R.layout.item_contact_display, null);
		if (labelValue!=null) {
			TextView tvLabel=(TextView) llShowItem.findViewById(R.id.item_label);
			tvLabel.setText(labelValue);
		}
		TextView tvContent=(TextView) llShowItem.findViewById(R.id.item_content);
		tvContent.setText(contentValue);
		showBlock.addView(llShowItem);
	}
	/**
	 * 是否是云好友
	 * @return
	 */
	private boolean isCloud() {
		if (contact.ownId==contact.contactId) {
			return false;
		}else {
			return contact.isReadOnly;
		}
	}
	/**
	 * 创建选择分组的泡泡窗口
	 */
	private void createSetGroupWindow() {
		View root = inflater.inflate(R.layout.dialog_list_view, null);
		((TextView)root.findViewById(R.id.title)).setText("请选择分组");
		root.findViewById(R.id.bottom).setVisibility(View.VISIBLE);
		final ArrayList<String> data=isCloud?MainActivity.cloudGroups:MainActivity.contactGroups;
		groupAdapter = new GroupAdapter(context,data,contact.groups);
		final ListView list=(ListView) root.findViewById(R.id.list);
		list.setAdapter(groupAdapter);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				CheckBox box=(CheckBox) view.findViewById(R.id.group_hander);
				box.setChecked(!box.isChecked());
				int count = list.getChildCount();
				groupAdapter.groupValues.clear();
				for(int i=0;i<count;i++){
					LinearLayout ll=(LinearLayout) list.getChildAt(i);
					String label = ((TextView)ll.getChildAt(0)).getText().toString();
					if (((CheckBox)ll.getChildAt(1)).isChecked()) {
						groupAdapter.addGroup(label);
					}
				}
			}
		});
		root.findViewById(R.id.btn_OK).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				contact.groups=groupAdapter.getCheckedValue();
				tvGroup.setText(groupAdapter.getCheckedValue());
				Log.i("test", "contact.groups="+contact.groups);
				winGroup.dismiss();
				new Thread(new Runnable() {
					public void run() {
						Looper.prepare();
						try {
							JSONObject json = JsonUtil.updateContactGroup(contact);
							Log.i("test", "json="+json);
							contact=NetUtil.editContact(context, json);
							handler.sendEmptyMessage(SET_GROUP_SUCCESS);
						} catch (Exception e) {
							Log.i("test", e.getMessage(),e);
							handler.sendEmptyMessage(SET_GROUP_ERROR);
						}
					}
				}).start();
			}
		});
		root.findViewById(R.id.btn_Cancel).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				winGroup.dismiss();
			}
		});
		winGroup = new PopupWindow(root,300, ViewGroup.LayoutParams.WRAP_CONTENT);
		winGroup.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
		winGroup.setFocusable(true);
	}
	/**
	 * 显示选择分组的对话框，根据是我的信息还是其他联系人信息，对话框的位置不同
	 */
	private void showSetGroupWindow(){
		groupAdapter.notifyDataSetChanged();
		int gravity=contact.contactId==contact.ownId?Gravity.BOTTOM|Gravity.LEFT:Gravity.BOTTOM|Gravity.RIGHT;
		winGroup.showAtLocation(this, gravity, 63, 0);
	}
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SET_GROUP_SUCCESS:
				Toast.makeText(context, "设置分组成功", 300).show();
				break;
			case SET_GROUP_ERROR:
				Toast.makeText(context, "设置分组失败", 300).show();
				break;
			}
		}
	};
	private View llGroup;
	/**
	 * 得到contact对象
	 * @return
	 */
	public Contact getContact(){
		return contact;
	}
}
